package com.wuwangfu.transfor;

import org.apache.flink.streaming.api.datastream.ConnectedStreams;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoFlatMapFunction;
import org.apache.flink.streaming.api.functions.co.CoMapFunction;
import org.apache.flink.util.Collector;

/**
 * @Author jcshen
 * @Date 2023-02-23
 * @PackageName:com.wuwangfu.transfor
 * @ClassName: ConnectTransf
 * @Description:
 * @Version 1.0.0
 *
 * https://nightlies.apache.org/flink/flink-docs-release-1.14/docs/dev/datastream/operators/overview/#connect
 * 将两条流连接到一起，貌合神离，表面上是一条流，实际上还是两条流，可以连接不同类型的流
 * 两个流可以共享状态，可以实现interval join
 */
public class ConnectTransf {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> word = env.socketTextStream("localhost", 8888);
        SingleOutputStreamOperator<Integer> nums = env.socketTextStream("localhost", 9999).map(s -> Integer.parseInt(s));
        //将两个流connect
        ConnectedStreams<String, Integer> connected = word.connect(nums);

        SingleOutputStreamOperator<String> maped = connected.map(new CoMapFunction<String, Integer, String>() {
            //对第一个流进行map运算的方法
            @Override
            public String map1(String value) throws Exception {
                return value.toUpperCase();
            }

            //对第二个流进行map运算的方法
            @Override
            public String map2(Integer value) throws Exception {
                return "-" + value * 10;
            }
            /*这两个流的map方法执行完成的返回值会放入到新的流中，进行返回*/
        });
        //maped.print();

        /*输入一行，返回领到多行*/
        SingleOutputStreamOperator<Integer> flated = connected.flatMap(new CoFlatMapFunction<String, Integer, Integer>() {
            @Override
            public void flatMap1(String value, Collector<Integer> out) throws Exception {
                out.collect(Integer.valueOf(value));
            }

            @Override
            public void flatMap2(Integer value, Collector<Integer> out) throws Exception {
                out.collect(value * 10);
            }
        });
        flated.print();

        env.execute();
    }
}
